import { useEffect, useState, useCallback, useRef } from 'react';
import { List, Checkbox } from 'antd-mobile';
import service from './service';
import SimpleListView from '@inbiz/basic/SimpleListView';
import styles from './index.less';
import SearchBar from '../SyncComponents/WapSearchBar';
// import StateImage from '../StateImage';
import SelectBar from './SelectBar';
import { getLowercase } from './utils/index';

export default function UserTab(props: any) {
  const listRef = useRef<any>();
  const [pageNum, _pageNum] = useState(1);
  const [searchValue, _searchValue] = useState('');
  const [data, _data] = useState<any[]>([]);
  const [hasMore, _hasMore] = useState(true);
  const [loadingMore, _loadingMore] = useState(false);
  const { selected, selectedId, allSelected, multiple, onOk, onCancel, setSelected, tabKey } =
    props;

  const onRefresh = useCallback(
    (params: any) => {
      let searchKey = params?.searchValue != null ? params?.searchValue : searchValue;
      service
        .getUserList({
          departmentId: 1,
          searchContent: searchKey,
          isChild: true,
          pageNum: 1,
          pageSize: 30,
        })
        .then((res) => {
          if (res) {
            _data(getLowercase(res?.Info, tabKey) || []);
            _pageNum(1);
            _hasMore(!!(res?.Info || []).length);
            // 每次刷新滚动到顶部
            listRef.current?.scroll(0, 0);
          }
        });
    },
    [searchValue],
  );

  const onRowSelectChange = useCallback(
    (row: any) => {
      return (checked: boolean) => {
        if (props.updateSelected) {
          props.updateSelected && props.updateSelected(checked, row);
        } else {
          let index = selectedId.indexOf(row?.key);
          if (checked) {
            if (index == -1) {
              let newSelected = [...selected, row];
              setSelected(newSelected);
            }
          } else {
            if (index > -1) {
              let newSelected = [...selected];
              newSelected.splice(index, 1);
              setSelected(newSelected);
            }
          }
        }
      };
    },
    [selectedId, selected],
  );

  const loadMore = useCallback(() => {
    if (!hasMore) return;
    if (loadingMore) return;
    _loadingMore(true);
    service
      .getUserList({
        departmentId: 1,
        searchContent: searchValue,
        isChild: true,
        pageNum: pageNum + 1,
        pageSize: 30,
      })
      .then((res) => {
        if (res) {
          let newData = [...data.concat(res.Info || [])];
          _hasMore(!!(res.Info || []).length);
          _data(getLowercase(newData, tabKey) || []);
          _pageNum(pageNum + 1);
          _loadingMore(false);
        } else {
          _loadingMore(false);
        }
      })
      .catch((e) => {
        _loadingMore(false);
      });
  }, [hasMore, loadingMore, pageNum, data, searchValue]);

  const onSearch = (value: string) => {
    _searchValue(value);
    onRefresh({ searchValue: value });
  };

  const onChange = useCallback(
    (v) => {
      if (searchValue && !v) {
        _searchValue('');
        onRefresh({ searchValue: '' });
      }
      _searchValue(v);
    },
    [searchValue],
  );

  useEffect(() => {
    service
      .getUserList({
        departmentId: 1,
        searchContent: '',
        isChild: true,
        pageNum: 1,
        pageSize: 30,
      })
      .then((res) => {
        if (res) {
          _data(getLowercase(res?.Info, tabKey) || []);
          _pageNum(1);
          _hasMore(!!(res.Info || []).length);
        }
      });
  }, []);

  return (
    <div className={styles.userTab}>
      <SearchBar
        editable
        value={searchValue}
        onSearch={onSearch}
        onChange={onChange}
        showCancelButton={false}
      />
      <SimpleListView
        style={{
          height: 'calc(100% - 36px)',
        }}
        ref={listRef}
        onRefresh={onRefresh}
        loadMore={loadMore}
        hasMore={hasMore}
        renderRow={(row: any, index: number) => {
          return (
            <List.Item
              key={index}
              // 新接口没返回用户image
              // prefix={
              //   <StateImage
              //     width={30}
              //     height={30}
              //     style={{ borderRadius: '50%', verticalAlign: 'middle' }}
              //     src={row.UserIcon}
              //     errorImage={require('@public/resource/icons/member-user.png')}
              //   />
              // }
              extra={
                <Checkbox
                  checked={selectedId.includes(row?.key)}
                  onChange={onRowSelectChange(row)}
                />
              }
            >
              <span
                dangerouslySetInnerHTML={{
                  __html: row.name.replace(
                    searchValue,
                    `<span class='Highlighter'>${searchValue}</span>`,
                  ),
                }}
              ></span>
              <span
                dangerouslySetInnerHTML={{
                  __html: `(${row.userloginname.replace(
                    searchValue,
                    `<span class='Highlighter'>${searchValue}</span>`,
                  ) || ''
                    })`,
                }}
              ></span>
            </List.Item>
          );
        }}
        dataSource={data}
      />
      <SelectBar
        filterKey={tabKey}
        data={data}
        selectedId={selectedId}
        selected={selected}
        allSelected={allSelected}
        multiple={multiple}
        setSelected={setSelected}
        onOk={onOk}
        onCancel={onCancel}
      />
    </div>
  );
}
